package net.vsame.sqlmanger.mysql;

import java.util.Map;

import net.vsame.sqlmanger.helper.UserHelper;
import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.helper.WebHelper;
import net.vsame.url2sql.utils.JdbcUtils;

public class DataBaseManger {

	private static final String SUCCESS = "SUCCESS";
	private Url2SqlContext c;
	private Map<String, Object> map;
	private Long id;
	private String operate;
	private String databasename;
	private String status;
	private String databaseId;

	public DataBaseManger(){
		c = WebHelper.getContext();
		//c.setConn(conn);//更改权限
		id = c.getParamByType(Long.class, "id");
		String sql = "SELECT a.operate, a.status, d.databasename, d.id 'databaseId' FROM database_apply_t a, database_t d where a.databaseId=d.id and a.id=${id}";
		map = SqlHelper.queryOne(sql , null);
		if(map == null){
			c.putError(1, "数据有误");
		}else{
			status = map.get("status")+"";
			operate = map.get("operate")+"";
			databasename = map.get("databasename")+"";
			databaseId = map.get("databaseId")+"";
		}
	}
	
	public void operate(){
		if(map == null){
			return ;
		}
		if(!"APPLY".equals(status)){
			c.putError(1, "请勿重复操作");
			return ;
		}
		String result = c.getParam("type");
		if(!SUCCESS.equalsIgnoreCase(result)){
			updateStatus("FAIL");
			return ;
		}
		updateStatus(SUCCESS);
		if("CREATE".equalsIgnoreCase(operate)){
			createDatabase();
		}
		else if("DROP".equalsIgnoreCase(operate)){
			dropDatabase();
		}
	}
	
	private void updateStatus(String status){
		String sql = "UPDATE `database_apply_t` SET `status`=?, handlerId=? WHERE `id`=?";
		JdbcUtils.execute(sql, status, UserHelper.getUserId(), id);
	}
	
	private void createDatabase(){
		String sql = "create database " + databasename + " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
		JdbcUtils.execute(sql);
	}
	
	private void dropDatabase(){
		//设置表字段
		String sql = "UPDATE `database_t` SET `removed`='Y' WHERE id=" +databaseId;
		JdbcUtils.execute(sql);
		//删除库
		JdbcUtils.execute("drop database IF EXISTS "+databasename);
	}
	
}
